import { login, logout, getInfo, loginBySms } from '@/framework/api/user'
import { getToken, setToken, removeToken } from '@/framework/utils/auth'
import { resetRouter } from '@/router'
import { encryption, decryption } from 'DQBasic-vue-component'
import store from '@/store'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    organizationId: '',
    avatar: '',
    userId: '',
    roles: [],
    authorities: [],
    wsUrl: '',
    infornum: 0,
    isLock: false,
    passWorkConfig: {},
    account: '',
    tenantName: '',
    tenantId: '',
    roleNames: '',
    lastLoginTime: '',
    positionName: '',
    modifyFlag: '',
    groupId: ''
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ORGID: (state, organizationId) => {
    state.organizationId = organizationId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AUTHORITIES: (state, authorities) => {
    state.authorities = authorities
  },
  SET_WSURL: (state, wsUrl) => {
    state.wsUrl = wsUrl
  },
  SET_INFORNUM: (state, infornum) => {
    state.infornum = infornum
  },
  SET_LOCK(state, action) {
    state.isLock = true
    localStorage.setItem('isLock', state.isLock)
  },
  CLEAR_LOCK(state, action) {
    state.isLock = false
    localStorage.removeItem('isLock')
  },
  SET_PASSWORKCONFIG: (state, passWorkConfig) => {
    state.passWorkConfig = passWorkConfig
  },
  SET_ROLENAMES: (state, roleNames) => {
    state.roleNames = roleNames
  },
  SET_TENANTNAME: (state, tenantName) => {
    state.tenantName = tenantName
  },
  SET_TENANTID: (state, tenantId) => {
    state.tenantId = tenantId
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_LASTLOGINTIME: (state, lastLoginTime) => {
    state.lastLoginTime = lastLoginTime
  },
  SET_POSITIONNAME: (state, positionName) => {
    state.positionName = positionName
  },
  SET_MODIFYFLAG: (state, modifyFlag) => {
    state.modifyFlag = modifyFlag
  },
  SET_GROUPID: (state, groupId) => {
    state.groupId = groupId
  }
}

const actions = {
  login({ commit }, userInfo) {
    const password = encryption({
      data: userInfo
    })
    return new Promise((resolve, reject) => {
      login(password).then((response) => {
        const res = decryption(response)
        const { token } = res.data
        commit('SET_TOKEN', token)
        commit('SET_PASSWORKCONFIG', res.data)
        commit('SET_MODIFYFLAG', res.data)
        setToken(token)
        if (window.localStorage.getItem('servesList')) {
          window.localStorage.removeItem('servesList')
        }
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then((response) => {
        const { data } = response
        if (!data) {
          return reject(new Error('验证失败，请重新登录'))
        }
        const { userId, avatar, realName, roles, authorities, organizationId, wsUrl, account, tenantName, tenantId, roleNames, lastLoginTime, positionName, groupId } = data
        commit('SET_USERID', userId)
        commit('SET_NAME', realName)
        commit('SET_ORGID', organizationId)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        commit('SET_AUTHORITIES', authorities)
        commit('SET_WSURL', wsUrl)
        commit('SET_ACCOUNT', account)
        commit('SET_TENANTNAME', tenantName)
        commit('SET_TENANTID', tenantId)
        commit('SET_ROLENAMES', roleNames)
        commit('SET_LASTLOGINTIME', lastLoginTime)
        commit('SET_POSITIONNAME', positionName)
        commit('SET_GROUPID', groupId)

        // store.dispatch('websocket/WEBSOCKET_INIT', wsUrl)
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        commit('CLEAR_LOCK')
        dispatch('tagsView/delAllViews', {}, { root: true })
        if (window.localStorage.getItem('servesList')) {
          window.localStorage.removeItem('servesList')
        }
        store.state.websocket?.websock?.close()
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  smslogin({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginBySms(userInfo).then((res) => {
        const response = decryption(res)
        const { token } = response.data
        commit('SET_TOKEN', token)
        // commit('SET_PASSWORKCONFIG', res.data)
        setToken(token)
        // localStorage.setItem('realName', realName)
        // localStorage.setItem('loginUser', JSON.stringify(response.data.loginUser))
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

